
import { getNeedLoginPages, getTabbarPages } from '@/utils/pages.js'
//获取今日日期，格式YYYY-MM-DD
function getToday(){
	var date = new Date();
	var seperator1 = "-";
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

//获取明日日期，格式YYYY-MM-DD
function getTomorrow(){
	var date = new Date();
	date.setDate(date.getDate()+1);
	var seperator1 = "-";
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

function toast(title){
	
	uni.showToast({
		title:title,
		icon:'none'
	})
}

export {getToday,getTomorrow,toast}


export const showToast = (title, icon = "none") => {
    uni.showToast({
        title: title,
        icon: icon
    })
}

export const checkUserType = () => {
    let token = uni.getStorageSync('token');
    if (!token) {
        /* 跳到登录 */
        uni.reLaunch({
            url: '/pages/login'
        });
        return;
    }
}

export const validatePhone = (value) => {
    var reg = /^(1[3-9])\d{9}$/;
    if (value === "") {
        showToast('请填写手机号');
        return false;
    } else if (!reg.test(value)) {
        showToast('请输入正确的手机号！');
        return false;
    } else if (!(/^[0-9]*$/).test(value)) {
        showToast('请输入正确的手机号！');
        return false;
    } else {
        return true;
    }
}

export const validate_password = (value) => {
    var reg = /[^a-zA-z0-9!@#$%^&*()_+.]/g;
    if (value === '') {
        showToast('请输入新密码');
        return false;
    } else if (reg.test(value)) {
        showToast('密码只能输入大小写字母、数字和!@#$%^&*()_+.');
        return false;
    } else {
        return true;
    }
}

export const validate_account = (value) => {
    var reg = /[^a-zA-z0-9!@#$%^&*()_+.]/g;
    if (value === '') {
        showToast('请输入账号');
        return false;
    } else if (reg.test(value)) {
        showToast('账号只能输入大小写字母、数字和!@#$%^&*()_+.');
        return false;
    } else {
        return true;
    }
}

/**
 * 格式化日期
 * @param time
 * @param pattern
 * @returns {string|null}
 */
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null;
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time);
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time *= 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        if (result.length > 0 && value < 10) {
            value = `0${value}`;
        }
        return value || 0;
    });
    return time_str;
}

export const isWebView = () => {
    var systemInfo = uni.getSystemInfoSync();
    // 如果是在小程序环境中，则通过plus.runtime来判断
    if (/uni-app/i.test(systemInfo.ua)) {
        return true; // WebView环境
    }
    return false; // 其他环境，如App等
}

/**
 * 判断是否是url
 * @param str
 * @returns
 */
export function isUrl(str) {
    return str && (str.indexOf('http://') != -1 || str.indexOf('https://') != -1) || false
}

/**
 * 图片输出
 * @param path
 * @returns
 */
export function img(path) {
    return isUrl(path) ? path : `${import.meta.env.VITE_IMG_DOMAIN}/${path}`
}

/**
 * 获取token
 */
export function getToken() {
    return uni.getStorageSync('token')
}
export const queryParams = (param) => {
    return '?' + Object.keys(param).map(key => {
        return `${key}=${param[key]}`
    }).join('&');
}
/**
 * 跳转页面
 */
export const redirect = (redirect) => {

    let { url, mode, param, success, fail, complete } = redirect
    // 如果未开启普通账号登录注册,不展示登录注册页面
    if (!getToken() && getNeedLoginPages().indexOf(url) != -1) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        return
    }

    mode = mode || 'navigateTo'
    const tabBar = getTabbarPages()
    tabBar.includes(url) && (mode = 'switchTab')

    mode != 'switchTab' && param && Object.keys(param).length && (url += queryParams(param))

    switch (mode) {
        case 'switchTab':
            uni.switchTab({
                url,
                success: () => {
                    success && success()
                },
                fail: () => {
                    fail && fail()
                },
                complete: () => {
                    complete && complete()
                }
            })
            break;
        case 'navigateTo':
            uni.navigateTo({
                url,
                success: () => {
                    success && success()
                },
                fail: () => {
                    fail && fail()
                },
                complete: () => {
                    complete && complete()
                }
            })
            break;
        case 'reLaunch':
            uni.reLaunch({
                url,
                success: () => {
                    success && success()
                },
                fail: () => {
                    fail && fail()
                },
                complete: () => {
                    complete && complete()
                }
            })
            break;
        case 'redirectTo':
            uni.redirectTo({
                url,
                success: () => {
                    success && success()
                },
                fail: () => {
                    fail && fail()
                },
                complete: () => {
                    complete && complete()
                }
            })
            break;
    }
}


/**
 * 自定义跳转链接
 */
export const diyRedirect = (link) => {

    if (link == null || Object.keys(link).length == 0) return;

    // 外部链接
    if (link.url && (link.url.indexOf('https') != -1 || link.url.indexOf('http') != -1)) {

        // #ifdef H5
        window.location.href = link.url;
        // #endif

        // #ifdef MP
        redirect({
            url: '/pages/webview/index',
            param: { src: encodeURIComponent(link.url) }
        });
        // #endif
    } else if (link.appid) {
        // 跳转其他小程序

        // #ifdef MP
        uni.navigateToMiniProgram({
            appId: link.appid,
            path: link.page
        })
        // #endif
    } else if (link.name == 'DIY_MAKE_PHONE_CALL' && link.mobile) {
        // 拨打电话

        uni.makePhoneCall({
            phoneNumber: link.mobile,
            success: (res) => { },
            fail: (res) => { }
        });

    } else {
        redirect({ url: link.url });
    }
}

/**
 * 设置登录返回页
 */
export const setLoginBack = (data) => {
    uni.setStorage({ key: 'loginBack', data })
    setTimeout(() => {
        redirect({ url: '/pages/login', mode: 'redirectTo' })
    })
}

/**
 * 执行登录后跳转
 */
export const handleLoginBack = () => {
    uni.getStorage({
        key: 'loginBack',
        success: (data) => {
            uni.removeStorageSync('loginBack')
            data ? redirect(data.data) : redirect({ url: '/pages/index/index', mode: 'switchTab' })
        },
        fail: (res) => {
            redirect({ url: '/pages/index/index', mode: 'switchTab' })
        }
    })
}

const isArray = (value) => {
    if (typeof Array.isArray === 'function') {
        return Array.isArray(value)
    }
    return Object.prototype.toString.call(value) === '[object Array]'
}

/**
 * @description 深度克隆
 * @param {object} obj 需要深度克隆的对象
 * @returns {*} 克隆后的对象或者原值（不是对象）
 */
export function deepClone(obj) {
    // 对常见的“非”值，直接返回原来值
    if ([null, undefined, NaN, false].includes(obj)) return obj
    if (typeof obj !== 'object' && typeof obj !== 'function') {
        // 原始类型直接返回
        return obj
    }
    const o = isArray(obj) ? [] : {}
    for (const i in obj) {
        if (obj.hasOwnProperty(i)) {
            o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
        }
    }
    return o
}

/**
 * 金额格式化
 */
export function moneyFormat(money) {
    return isNaN(parseFloat(money)) ? money : parseFloat(money).toFixed(2)
}

/**
 * 判断是否为空
 */
export function isEmpty(value) {
    switch (typeof value) {
        case 'undefined':
            return true
        case 'string':
            if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true
            break
        case 'boolean':
            if (!value) return true
            break
        case 'number':
            if (value === 0 || isNaN(value)) return true
            break
        case 'object':
            if (value === null || value.length === 0) return true
            for (const i in value) {
                return false
            }
            return true
    }
    return false
}